package com.jiang.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;

import com.jiang.utils.FileUploadUtils;


public abstract class BaseAction {

	@Autowired
	private MessageSource messageSource;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sf, true));
	}
	
	public String createFileName(MultipartFile file) {
		if(!file.isEmpty()) {
			return FileUploadUtils.createFileName(file.getContentType());
		}else {
			return null;
		}
	}
	
	public boolean uploadFile(MultipartFile file,  HttpServletRequest request) {
		if(!file.isEmpty()) {
			System.out.println(request.getServletContext().getRealPath("/"));
			String filePath = request.getServletContext().getRealPath(this.getUploadDir())+ this.createFileName(file);
			return FileUploadUtils.save(file, new File(filePath));
		}
			return false;
	}
	
	public abstract String getUploadDir();
	
	/**
	 * 获取配置资源数据
	 * @param key
	 * @param args
	 * @return
	 */
	public String getResourceValue(String key,Object[] args) {
		
		return this.messageSource.getMessage(key, args, Locale.getDefault());
	}
	
	
	
}
